package jgl.vajra.management.manager;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import jgl.vajra.management.bean.AddressBean;
import jgl.vajra.management.widget.manager.RxJavaHttpManager;
import jgl.vajra.management.widget.manager.SPManager;
import jgl.vajra.management.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.management.widget.permissions.PermissionListener;
import jgl.vajra.management.widget.permissions.PermissionsUtil;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.CommonObserver;
import jgl.vajra.management.widget.utils.ToastUtils;

public class LocationLocalManager {

    private static class LocationLocalManagerSingleton {
        private static final LocationLocalManager INSTANCE = new LocationLocalManager();

    }

    public static LocationLocalManager getInstance() {
        return LocationLocalManager.LocationLocalManagerSingleton.INSTANCE;
    }

    private LocationLocalManager() {
    }

    public void initLocation(Context context) {

        String[] permissions = {
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.RECORD_AUDIO,
        };
        PermissionsUtil.requestPermission(context, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        initLocationManager(context);
                        startLoopUpload(context);
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        //  ToastUtils.showShort("请到设置-权限管理中开启");
                        AddressBean data = new AddressBean();
                        data.countryName = "中国";
                        data.countryCode = "CN";
                        data.adminArea = "北京市";
                        data.locality = "北京市";
                        data.subLocality = "东城区";
                        data.featureName = "";
                        data.latitude = 39.915119;
                        data.longitude = 116.403963;
                        SPManager.HomeData.saveAddressData(data);
                    }
                }, permissions, false, null
        );


    }

    private void initLocationManager(Context context) {
        //使用定位管理者获取定位坐标
        LocationManager systemService = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = systemService.getProviders(true);
        String provider = "";
        for (int i = 0; i < providers.size(); i++) {
            if (providers.contains(LocationManager.GPS_PROVIDER)) {
                provider = LocationManager.GPS_PROVIDER;
            } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                provider = LocationManager.NETWORK_PROVIDER;
            } else {
                ToastUtils.showShort("定位失败!");
            }
        }
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (TextUtils.isEmpty(provider)) {
            ToastUtils.showShort("检查权限是否开启!");
        } else {
            Location location = systemService.getLastKnownLocation(provider);
            if (location != null) {
//                location.getLocality()
                Logger.d("定位1  " + location.getLatitude() + "---" + location.getLongitude() + "--");
                getAddress(context, location.getLatitude(), location.getLongitude());
            }
            systemService.requestLocationUpdates(provider, 60000, 1, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }

                @Override
                public void onProviderEnabled(String provider) {
                }

                @Override
                public void onProviderDisabled(String provider) {
                }
            });
        }

      /*  //获取地理位置管理器
        LocationManager mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            Location l = mLocationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = l;
            }
        }
        uploadLocationInfo(bestLocation);
        Logger.d("initLocationManager" + bestLocation.getLatitude() + "----" + bestLocation.getLongitude());*/
    }

    public void getAddress(Context context, double latitude, double longitude) {
        //Geocoder通过经纬度获取具体信息
        Geocoder gc = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> locationList = gc.getFromLocation(latitude, longitude, 1);

            if (locationList != null && locationList.size() != 0) {
                Address address = locationList.get(0);
                String countryName = address.getCountryName();//国家
                String countryCode = address.getCountryCode();
                String adminArea = address.getAdminArea();//省
                String locality = address.getLocality();//市
                String subLocality = address.getSubLocality();//区
                String featureName = address.getFeatureName();//街道
                double latitudeAddress = address.getLatitude();
                double longitudeAddress = address.getLongitude();

                AddressBean data = new AddressBean();
                data.countryName = countryName;
                data.countryCode = countryCode;
                data.adminArea = adminArea;
                data.locality = locality;
                data.subLocality = subLocality;
                data.featureName = featureName;
                data.latitude = latitudeAddress;
                data.longitude = longitudeAddress;

                SPManager.HomeData.saveAddressData(data);
                Logger.d("countryName" + countryName + "countryCode" + countryCode + "adminArea" + adminArea
                        + "locality" + locality + "subLocality" + subLocality + "featureName" + featureName);
            }else {
                AddressBean data = new AddressBean();
                data.countryName = "中国";
                data.countryCode = "CN";
                data.adminArea = "北京市";
                data.locality = "北京市";
                data.subLocality = "东城区";
                data.featureName = "";
                data.latitude = 39.915119;
                data.longitude = 116.403963;
                SPManager.HomeData.saveAddressData(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void startLoopUpload(Context context) {
        Observable.interval(4, TimeUnit.HOURS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                initLocationManager(context);
            }
        });

    }

    private void uploadLocationInfo(Location bestLocation) {
        Map<String, Object> map = new HashMap<>();
        map.put("latitude", bestLocation.getLatitude());
        map.put("longitude", bestLocation.getLongitude());
        RetrofitJsonManager.getInstance().getApiService().uploadLocation(map).compose(RxJavaHttpManager.applyTransformer()).subscribe(new CommonObserver<Object>() {
        });

    }
}
